<template>
  <div class="course-management">
    <div class="header">
      <h2>课程管理</h2>
      <div class="header-right">
        <!-- <el-input
          v-model="searchQuery"
          placeholder="搜索课程名称"
          class="search-input"
          clearable
          @clear="handleSearch"
          @input="handleSearch"
        /> -->
        <el-button type="primary" @click="handleAdd">新增课程</el-button>
      </div>
    </div>

    <el-table
      :data="filteredCourseList"
      border
      style="width: 100%"
      v-loading="loading"
    >
      <el-table-column prop="courseName" label="课程名称" min-width="150" />
      <el-table-column prop="courseIntroduce" label="课程描述" min-width="200" show-overflow-tooltip />
      <el-table-column prop="difficulty" label="课程难度" width="100">
        <template #default="scope">
          <el-tag
            :type="scope.row.difficulty === 1 ? 'info' : scope.row.difficulty === 2 ? 'warning' : 'danger'"
            :style="{
              border: '1.5px solid',
              borderColor: scope.row.difficulty === 1 ? '#3EC8FF' : scope.row.difficulty === 2 ? '#FE7909' : '#FD4C40',
              color: scope.row.difficulty === 1 ? '#3EC8FF' : scope.row.difficulty === 2 ? '#FE7909' : '#FD4C40',
              background: '#fff'
            }"
            effect="plain"
            disable-transitions
          >
            {{ scope.row.difficulty === 1 ? '简单' : scope.row.difficulty === 2 ? '中等' : '困难' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="teacherIntroduce" label="教师描述" min-width="200" show-overflow-tooltip />
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        :model="courseForm"
        :rules="rules"
        ref="courseFormRef"
        label-width="100px"
      >
        <el-form-item label="课程名称" prop="courseName">
          <el-input v-model="courseForm.courseName" placeholder="请输入课程名称" />
        </el-form-item>
        <el-form-item label="课程描述" prop="courseIntroduce">
          <el-input
            v-model="courseForm.courseIntroduce"
            type="textarea"
            :rows="4"
            placeholder="请输入课程描述"
          />
        </el-form-item>
        <el-form-item label="课程难度" prop="difficulty">
          <el-select v-model="courseForm.difficulty" placeholder="请选择课程难度">
            <el-option label="简单" :value="1" />
            <el-option label="中等" :value="2" />
            <el-option label="困难" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="教师描述" prop="teacherIntroduce">
          <el-input
            v-model="courseForm.teacherIntroduce"
            type="textarea"
            :rows="2"
            placeholder="请输入教师描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getCourseListService,
  addCourseService,
  updateCourseService,
  deleteCourseService
} from '@/apis/course'

const courseList = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const courseFormRef = ref(null)

const courseForm = ref({
  courseId: null,
  courseName: '',
  courseIntroduce: '',
  difficulty: 1,
  teacherIntroduce: ''
})

const rules = {
  courseName: [
    { required: true, message: '请输入课程名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  courseIntroduce: [
    { max: 200, message: '长度不能超过 200 个字符', trigger: 'blur' }
  ],
  difficulty: [
    { required: true, message: '请选择课程难度', trigger: 'change' }
  ],
  teacherIntroduce: [
    { max: 200, message: '长度不能超过 200 个字符', trigger: 'blur' }
  ]
}

// 过滤后的课程列表
const filteredCourseList = computed(() => {
  if (!searchQuery.value) return courseList.value
  return courseList.value.filter(course =>
    course.courseName.toLowerCase().includes(searchQuery.value.toLowerCase())
  )
})

// 获取课程列表
const getCourseList = async () => {
  loading.value = true
  try {
    const res = await getCourseListService()
    if (res.code === 200 || res.code === 1000) {
      courseList.value = res.data
      total.value = res.data.length
    }
  } catch (error) {
    ElMessage.error('获取课程列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
}

// 新增课程
const handleAdd = () => {
  dialogTitle.value = '新增课程'
  courseForm.value = {
    courseId: null,
    courseName: '',
    courseIntroduce: '',
    difficulty: 1,
    teacherIntroduce: ''
  }
  dialogVisible.value = true
}

// 编辑课程
const handleEdit = (row) => {
  dialogTitle.value = '编辑课程'
  courseForm.value = { ...row }
  dialogVisible.value = true
}

// 删除课程
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该课程吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteCourseService(row.courseId)
      if (res.code === 200 || res.code === 1000) {
        ElMessage.success('删除成功')
        getCourseList()
      }
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

// 提交表单
const handleSubmit = async () => {
  if (!courseFormRef.value) return

  await courseFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const service = courseForm.value.courseId ? updateCourseService : addCourseService
        const res = await service(courseForm.value)
        if (res.code === 200 || res.code === 1000) {
          ElMessage.success(courseForm.value.courseId ? '更新成功' : '新增成功')
          dialogVisible.value = false
          getCourseList()
        }
      } catch (error) {
        ElMessage.error(courseForm.value.courseId ? '更新失败' : '新增失败')
      }
    }
  })
}

onMounted(() => {
  getCourseList()
})
</script>

<style scoped>
.course-management {
  padding: 20px;
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.header-right {
  display: flex;
  gap: 16px;
  align-items: center;
}
.search-input {
  width: 300px;
}
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 